package com.hnkywl.sts.action.cwgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.dao.cwgl.VoucherType;
import com.hnkywl.sts.entity.cwgl.Qtpz;
import com.hnkywl.sts.entity.cwgl.Qtpzfl;
import com.hnkywl.sts.entity.cwgl.VoucherItemData;
import com.hnkywl.sts.entity.cwgl.VoucherMasterData;
import com.hnkywl.sts.entity.cwgl.kmys.Tyfzhsmc;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.service.cwgl.QtpzService;
import com.hnkywl.sts.service.cwgl.VoucherService;
import com.hnkywl.sts.service.cwgl.kmys.TyfzhsmcService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.UUIDGenerator;
import com.hnkywl.sts.util.XmlParse;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Type;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-5-18
 * Time: 下午1:58
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/cwgl/qtpz")
public class QtpzAction extends SimpleActionSupport {
    private Long id;
    //其他凭证
    private Qtpz qtpz;
    //分页组件 起始位置
    private int page;
    //分页组件 页面大小
    private int rows;
    //状态
    private Integer status;
    //保存状态
    private Integer saveStatus;
    //开始时间
    private Date startDate;
    //结束时间
    private Date endDate;
    //公司ID
    private Long companyId;
    //单据号
    private Long no;
    //凭证号
    private Integer voucherNo;
    //制单人
    private String createUser;
    //时间
    private Date date;
    //操作
    private String operation;
    //凭证分录信息
    private Map<String, Object> voucher;
    //久其财务借口返回结果
    private Map<String, String> result = new HashMap<String, String>();

    private List<Tyfzhsmc> tyfzhsmcList;

    private Gson gson = new Gson();
    //解析久其借口返回的xml
    private XmlParse xmlParse;

    private QtpzService qtpzService;

    private TyfzhsmcService tyfzhsmcService;

    private VoucherService voucherService;

    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;
    private String word;

    @Action("qtpz")
    public String qtpz() {
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        return SUCCESS;
    }

    @Action("pzz")
    public void pzz() {
        this.renderJson(qtpzService.findPzz());
    }

    @Action("qtpzList")
    public void qtpzList() {
        if (startDate != null)
            startDate = convertDate(startDate, true);
        if (endDate != null)
            endDate = convertDate(endDate, false);
        this.renderJson(qtpzService.findQtpz(status, saveStatus, startDate, endDate, companyId, no, voucherNo, word, createUser, page, rows));
    }

    @Actions({@Action("qtpz_content"), @Action("qtpz_import_content")})
    public String qtpzContent() {
        createUser = YgService.getCurrentYgName();
        tyfzhsmcList = tyfzhsmcService.findAll();
        date = new Date();
        if (id != null) {
            qtpz = qtpzService.findQtpz(id);
        }
        return SUCCESS;
    }

    @Action("findQtpzfl")
    public void findQtpzfl() {
        renderText(qtpzService.findQtpzfl(id));
    }

    @Action("save")
    public void save() {
        try {
            qtpzService.saveQtpz(qtpz);
            renderText("{\"statusCode\":\"200\", \"message\":\"保存成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("update")
    public void update() {
        try {
            qtpzService.updateQtpz(qtpz);
            renderText("{\"statusCode\":\"200\",\"message\":\"修改成功！\"}");
        } catch (RuntimeException e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("delete")
    public void delete() {
        try {
            qtpzService.deleteQtpz(id);
            renderText("{\"statusCode\":\"200\", \"message\":\"删除成功！\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("copy")
    public void copy() {
        try {
            qtpzService.copyQtpz(qtpz);
            renderText("{\"statusCode\":\"200\",\"message\":\"复制成功！\"}");
        } catch (RuntimeException e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 导入凭证
     */
    @Action("generate_voucher")
    public void generateVoucher() {
        try {
            voucherService.checkJiuqiUsernamePassword();
            String uuid = UUIDGenerator.getUUID();
            Integer year = GregorianCalendar.getInstance().get(Calendar.YEAR);
            Integer mouth = GregorianCalendar.getInstance().get(Calendar.MONTH);
            Boolean begin = voucherService.beginGenerateVoucher(id, VoucherType.QTPZ);
            if (!begin)
                throw new RuntimeException("其他用户已经开始导入该凭证，请选择其他凭证进行导入!");
            //凭证分录
            //voucher = qtpzService.getVoucherItems(id, uuid);
            voucher = qtpzService.getU8VoucherItems(id, uuid);
            //凭证头
            Map<String, Object> msgheader = voucherService.getMsgHeader();
            voucher.put("msgheader", msgheader);
            //凭证主表信息
            Map<String, Object> voucherMaster = qtpzService.getVoucherMaster(id, uuid);
            voucherMaster.put("memo", VoucherType.QTPZ.getTag() + id);//备注，在凭证删除时使用
            voucher.put("master", voucherMaster);
            String r = voucherService.generateVoucher(voucher);
            result = xmlParse.getContent(r);
            //结果回写
            if ("1".equals(result.get(XmlParse.RESPONSEFLAG))) {
                String vchrid = result.get(XmlParse.VCHRID);
                String vchrnum = result.get(XmlParse.VCHRNUM);
                Boolean success = voucherService.generateVoucherSuccess(uuid, vchrid, vchrnum, year, id, VoucherType.QTPZ);
                if (!success)
                    throw new RuntimeException("凭证导入成功，但凭证信息回写失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put(XmlParse.RESPONSEFLAG, "0");
            result.put(XmlParse.RESPONSEMESSAGE, e.getMessage());
        }
        renderJson(gson.toJson(result));
    }

    /**
     * 撤销凭证
     */
    @Action("revoke_voucher")
    public void revokeVoucher() {
        try {
            voucherService.checkJiuqiUsernamePassword();
            Boolean begin = voucherService.beginRevokeVoucher(id, VoucherType.QTPZ);
            if (!begin)
                throw new RuntimeException("其他用户已经开始撤销该凭证，请选择其他凭证进行撤销!");
            Map<String, Object> msgheader = voucherService.getMsgHeader();
            Map<String, Object> revokeInfo = qtpzService.getRevokeInfo(id);
            Map<String, Object> info = new HashMap<String, Object>();
            info.put("msgheader", msgheader);
            info.put("revokeinfo", revokeInfo);
            revokeInfo.put("memo", VoucherType.QTPZ.getTag() + id);//备注，在凭证删除时使用
            String r = voucherService.revokeVoucher(info);
            result = xmlParse.getContent(r);
            //结果回写
            if ("1".equals(result.get(XmlParse.RESPONSEFLAG))) {
                Boolean success = voucherService.revokeVoucherSuccess(id, VoucherType.QTPZ);
                if (!success)
                    throw new RuntimeException("凭证撤销成功，但凭证状态回写失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put(XmlParse.RESPONSEFLAG, "0");
            result.put(XmlParse.RESPONSEMESSAGE, e.getMessage());
        }
        renderJson(gson.toJson(result));
    }

    /**
     * 重置凭证
     */
    @Action("rest_voucher")
    public void restVoucher() {
        renderJson(voucherService.restVoucher(id, VoucherType.QTPZ));
    }

    /**
     * 重置凭证
     */
    @Action("sync_voucher_num")
    public void syncVoucherNum() {
        try {
            String uuid = UUIDGenerator.getUUID();
            voucherService.checkJiuqiUsernamePassword();
            //凭证主表信息
            Map<String, Object> voucherMaster = qtpzService.getVoucherMaster(id, uuid);
            Map<String, Object> revokeInfo = qtpzService.getRevokeInfo(id);
            Map<String, Object> info = new HashMap<String, Object>();
            info.put("master", voucherMaster);
            info.put("revokeinfo", revokeInfo);
            String r = voucherService.syncVoucher(info);
            result = xmlParse.getContent(r);
            if ("1".equals(result.get(XmlParse.RESPONSEFLAG))) {
                String temp = result.get(XmlParse.VCHRNUM);
                voucherService.syncVoucher(id, Integer.parseInt(temp), VoucherType.QTPZ);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put(XmlParse.RESPONSEFLAG, "0");
            result.put(XmlParse.RESPONSEMESSAGE, e.getMessage());
        }
        renderJson(gson.toJson(result));
    }

    /**
     * @param date
     * @param flag true:当天00:00:00   false:第二天00:00:00
     * @return
     */

    private Date convertDate(Date date, boolean flag) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        if (!flag)
            gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
        gc.set(GregorianCalendar.HOUR, 0);
        gc.set(GregorianCalendar.MINUTE, 0);
        gc.set(GregorianCalendar.SECOND, 0);
        return gc.getTime();
    }
    //=============getter setter====================

    public Qtpz getQtpz() {
        return qtpz;
    }

    public void setQtpz(Qtpz qtpz) {
        this.qtpz = qtpz;
    }

    //================setter====================
    public void setId(Long id) {
        this.id = id;
    }

    public void setSaveStatus(Integer saveStatus) {
        this.saveStatus = saveStatus;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public void setCompanyId(Long companyId) {
        this.companyId = companyId;
    }

    public void setNo(Long no) {
        this.no = no;
    }

    public void setVoucherNo(Integer voucherNo) {
        this.voucherNo = voucherNo;
    }
//==================getter==================

    public Date getDate() {
        return date;
    }

    public List<Tyfzhsmc> getTyfzhsmcList() {
        return tyfzhsmcList;
    }

//================getter setter================

    public String getOperation() {
        return operation;
    }

    public void setOperation(String operation) {
        this.operation = operation;
    }

    public String getCreateUser() {
        return createUser;
    }

    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    public void setGnczList(List<Gncz> gnczList) {
        this.gnczList = gnczList;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }

    @Autowired
    public void setQtpzService(QtpzService qtpzService) {
        this.qtpzService = qtpzService;
    }

    @Autowired
    public void setVoucherService(VoucherService voucherService) {
        this.voucherService = voucherService;
    }

    @Autowired
    public void setXmlParse(XmlParse xmlParse) {
        this.xmlParse = xmlParse;
    }

    @Autowired
    public void setTyfzhsmcService(TyfzhsmcService tyfzhsmcService) {
        this.tyfzhsmcService = tyfzhsmcService;
    }
}
